import React, { useEffect, useState, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { motion } from 'framer-motion';

const GitHubCallback: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [countdown, setCountdown] = useState(5);
  const { loginWithGithub } = useAuth();
  const history = useHistory();
  const location = useLocation();
  const processedRef = useRef(false);

  useEffect(() => {
    const handleGitHubCallback = async () => {
      // 防止重复执行（解决React.StrictMode导致的重复调用问题）
      if (processedRef.current) {
        console.log('GitHub callback already processed, skipping...');
        return;
      }
      processedRef.current = true;
      
      try {
        console.log('Processing GitHub callback...');
        // Get authorization code from URL parameters
        const urlParams = new URLSearchParams(location.search);
        const code = urlParams.get('code');
        const error = urlParams.get('error');
        const errorDescription = urlParams.get('error_description');
        const state = urlParams.get('state');

        if (error) {
          let errorMessage = 'GitHub authorization failed';
          if (error === 'access_denied') {
            errorMessage = 'You cancelled GitHub authorization, please try logging in again';
          } else if (errorDescription) {
            errorMessage = `GitHub authorization failed: ${errorDescription}`;
          } else {
            errorMessage = `GitHub authorization failed: ${error}`;
          }
          throw new Error(errorMessage);
        }

        if (!code) {
          throw new Error('GitHub authorization code not received, please try logging in again');
        }

        // Login using authorization code
        await loginWithGithub(code);
        
        // Login successful, redirect to design gallery page
        history.push('/design-gallery');
      } catch (error: any) {
        console.error('GitHub login callback processing failed:', error);
        let userFriendlyMessage = error.message || 'GitHub login failed, please try again';
        
        // Handle specific error types with user-friendly messages
        if (error.message?.includes('authorization code expired') || error.message?.includes('授权码已过期')) {
          userFriendlyMessage = 'Authorization code expired, please log in to GitHub again';
        } else if (error.message?.includes('network') || error.message?.includes('网络')) {
          userFriendlyMessage = 'Network connection failed, please check your network and try again';
        } else if (error.message?.includes('server') || error.message?.includes('服务器')) {
          userFriendlyMessage = 'Server temporarily unavailable, please try again later';
        }
        
        setError(userFriendlyMessage);
        setIsLoading(false);
        
        // Start countdown
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              history.push('/login');
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      }
    };

    handleGitHubCallback();
  }, [location.search, loginWithGithub, history]);

  const handleRetry = () => {
    history.push('/login');
  };

  // Cleanup timers
  useEffect(() => {
    return () => {
      // Clean up all timers when component unmounts
    };
  }, []);

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="max-w-md w-full space-y-8 bg-white p-10 rounded-2xl shadow-xl text-center"
        >
          <div>
            <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
              <svg
                className="h-6 w-6 text-red-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
                />
              </svg>
            </div>
            <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
              Login Failed
            </h2>
            <p className="mt-2 text-center text-sm text-red-600">
              {error}
            </p>
            <p className="mt-4 text-center text-sm text-gray-500">
              {countdown > 0 ? `Redirecting to login page in ${countdown} seconds...` : 'Redirecting...'}
            </p>
            <div className="mt-6 space-y-3">
              <button
                onClick={handleRetry}
                className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
              >
                Try Again
              </button>
              <button
                onClick={() => history.push('/')}
                className="w-full flex justify-center py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
              >
                Back to Home
              </button>
            </div>
          </div>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="max-w-md w-full space-y-8 bg-white p-10 rounded-2xl shadow-xl text-center"
      >
        <div>
          <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-blue-100">
            <svg
              className="animate-spin h-6 w-6 text-blue-600"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              ></path>
            </svg>
          </div>
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
            Processing GitHub Login
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600">
            Please wait, we are verifying your GitHub account...
          </p>
        </div>
      </motion.div>
    </div>
  );
};

export default GitHubCallback;